<?php

class UserController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
    }

    public function registerAction()
    {
       $form = new Application_Form_RegisterUser();
       
       if($this->getRequest()->isPost()) {
           // Hier kommt die Formularverarbeitung rein
           $postData = $this->getRequest()->getPost();
           
           $regModel = new Application_Model_RegisterUser($postData, $form);
           $regModel->check();
           $regModel->isDataValid();
           $errors = $regModel->getErrors();
           if($errors == null) {
               $regModel->saveData();
           } else {
               $this->view->errors = $errors;
           }           
       } 
       
       $this->view->form = $form;
    }

    public function loginAction()
    {
        // Default Db Adapter für die spätere Authorisierung holen
        $db = Zend_Db_Table::getDefaultAdapter();
        
        // Login Formular für die Datenvaldierung erstellen
        $loginForm = new Application_Form_Login();
        
        // Formulardaten validieren und entsprechend reagieren
        if($loginForm->isValid($this->getRequest()->getPost())) {
            
            $adapter = new Zend_Auth_Adapter_DbTable(
                    $db,
                    'user',
                    'name',
                    'pw',
                    'MD5(?)'
            );
            
            $adapter->setIdentity($loginForm->getValue('name'));
            $adapter->setCredential($loginForm->getValue('pw'));
            
            $result = Zend_Auth::getInstance()->authenticate($adapter);
            
            if($result->isValid()) {
                Zend_Debug::dump($adapter->getResultRowObject());
            }
            
        } else {
            $this->_forward('show-login-form');
        }
        
    }

    public function logoutAction()
    {
        // action body
    }

    public function showLoginFormAction()
    {
        $loginForm = new Application_Form_Login();
        
        if($this->getRequest()->isPost()) {
            Zend_Debug::dump($this->getRequest()->getPost());
        }
        
        $this->view->loginForm = $loginForm;    }


}
